﻿using System.Web;
using System.Xml.Linq;
using EPiServer.Core;
using PageTypeBuilder.UI;
using TemplateFoundation.Core;
using TemplateFoundation.Feeds;
using TemplateFoundation.PageTypes;

namespace TemplateFoundation.PageTemplates
{
    /// <summary>
    /// Base class for page templates used to output RSS feeds
    /// </summary>
    /// <seealso cref="RssPageBase"/>
    public class RssPageTemplateBase : SimplePage<RssPageBase>
    {
        /// <summary>
        /// Renders the RSS XML feed
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            Response.Clear();
            Response.ContentType = "text/xml";
            Xml.Save(HttpContext.Current.Response.Output);
            Response.End();
        }

        /// <summary>
        /// Gets the XML of the RSS feed
        /// </summary>
        public virtual XDocument Xml
        {
            get
            {
                var rss = new RssChannel(CurrentPage.Title, PageReference.StartPage.GetPage().GetFriendlyUrl(true), CurrentPage.Description);

                foreach (PageData article in CurrentPage.Pages)
                {
                    rss.AddItem(new RssItem((PageTypeBase)article, CurrentPage.IncludeFullContent));
                }

                return rss.Xml;
            }
        }
    }
}
